/*
 * 文件名： WcPayPabServiceImpl.java
 * 
 * 工程名称: bis-service
 *
 * Gopay
 *
 * 创建日期： 2017年8月10日
 *
 * Copyright(C) 2017, by www.gopay.com.cn Inc.All rights reserved.
 *
 * 原始作者: 宣广海
 *
 */
package com.gopay.bis.service.bank.impl.wcpay;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;

import com.gopay.bis.common.util.BankLogUtils;
import com.gopay.bis.manager.bank.wcpay.WcPayPabManager;
import com.gopay.common.Result;
import com.gopay.common.constants.bank.BankConstants;
import com.gopay.common.constants.proccode.ProcCodeConstants;
import com.gopay.common.domain.bank.BaseMessage;
import com.gopay.common.domain.bank.pab.agpay.PabTransResMsg;
import com.gopay.common.domain.bank.pab.agpay.res.PayOrderResMsg;
import com.gopay.common.domain.bank.pab.agpay.res.PayRefundQueryResMsg;
import com.gopay.common.domain.bank.pab.agpay.res.PayRefundResMsg;
import com.gopay.common.domain.bank.pab.agpay.res.PayStatusResMsg;
import com.gopay.common.domain.bank.wechat.scan.res.ScanPayServerNotifyMsg;
import com.gopay.common.domain.bank.wechat.wcpay.citic.res.WcPayNotifyMsg;
import com.gopay.common.domain.bank.wechat.wcpay.citic.res.WcPayResMsg;
import com.gopay.common.exception.GopayException;
import com.gopay.common.util.FastJsonUtil;
import com.gopay.common.util.TransUtil;
import com.gopay.remote.bank.WcPayInteractRemoteService;

/**
 * 微信公众号支付/支付宝服务窗支付民生银行渠道业务处理
 *
 * @author 宣广海
 *
 * @version
 *
 * @since 2017年8月10日
 */
public class WcPayPabServiceImpl implements WcPayInteractRemoteService {

	private static Logger logger = LoggerFactory.getLogger(WcPayPabServiceImpl.class);

	@Resource(name = "wcPayPabManager")
	private WcPayPabManager wcPayPabManager;

	@Override
	public Result pay(BaseMessage msg) throws GopayException {

		logger.info("------------WcPayPabServiceImpl pay start-------------");
		long beginTime = System.currentTimeMillis();

		Result result = new Result(false);
		try {
			@SuppressWarnings("unchecked")
			PabTransResMsg<PayOrderResMsg> resMessage = (PabTransResMsg<PayOrderResMsg>) wcPayPabManager.scanPay(msg);
			/**
			 * 定义返回对象
			 */
			WcPayResMsg respMsg = new WcPayResMsg();
			PayOrderResMsg payMsgBody = (PayOrderResMsg) resMessage.getBody();
			String jsapiJson=null;
			Map<String,String> jsmap=new HashMap<String,String>();
			if (StringUtils.equalsIgnoreCase("0", resMessage.getErrcode())) {
				if(BankConstants.BANK_LOGO_WECHAT.equals(msg.getOutStlmCd())){
					BeanUtils.copyProperties(resMessage, respMsg);
					jsmap.put("appId", payMsgBody.getAppId());
					jsmap.put("timeStamp", payMsgBody.getTimeStamp());
					jsmap.put("nonceStr", payMsgBody.getNonceStr());
					jsmap.put("signType", payMsgBody.getSignType());
					jsmap.put("package", payMsgBody.getWcpPackage());
					jsmap.put("paySign", payMsgBody.getPaySign());
					jsapiJson=FastJsonUtil.collectToString(jsmap);
				}else if(BankConstants.BANK_LOGO_ALIPAY.equals(msg.getOutStlmCd())){
					jsapiJson=payMsgBody.getTrade_no();
				}
				logger.info("------ return jsonStr:" + jsapiJson);
				respMsg.setPayInfo(jsapiJson);
				result.setDefaultModel(respMsg);
				result.setSuccess(true);
			} else {				
				result.setResultCode(ProcCodeConstants.PROC_CODE_100E1159);
				if(BankConstants.BANK_LOGO_ALIPAY.equals(msg.getOutStlmCd())){
					result.setResultCode(ProcCodeConstants.PROC_CODE_100E1162);
				}
				result.setErrorMsg(resMessage.getMsg());
				result.setSuccess(false);
			}
		} catch (GopayException e) {
			BankLogUtils.printServiceImplExceptionLog(e);
			result.setResultCode(e.getErrCode());
		} catch (Exception ex) {
			BankLogUtils.printServiceImplExceptionLog(ex);
			result.setResultCode(ProcCodeConstants.PROC_CODE_100E7025);
		}
		long endTime = System.currentTimeMillis();
		logger.info("------ WcPayPabServiceImpl pay end，耗时(ms):" + (endTime - beginTime));
		return result;

	}

	@SuppressWarnings("unchecked")
	@Override
	public Result orderQuery(BaseMessage msg) throws GopayException {
		Result result = new Result();
		try {
			PabTransResMsg<PayStatusResMsg> resMessage = (PabTransResMsg<PayStatusResMsg>) wcPayPabManager
					.orderQuery(msg);
			logger.info("---微信公众号/支付宝服务窗支付平安渠道订单查询返回处理对象：" + ToStringBuilder.reflectionToString(resMessage));
			if (("".equals(resMessage.getBody().getTrade_amount()))
					|| (null == resMessage.getBody().getTrade_amount())) {
				resMessage.setAmount(msg.getAmount());
			} else {
				resMessage.setAmount(new BigDecimal(
						TransUtil.amountConvert2Yuan(String.valueOf(resMessage.getBody().getTrade_amount()))));
			}
			result.setDefaultModel(resMessage);
			result.setSuccess(true);
		} catch (GopayException e) {
			BankLogUtils.printServiceImplExceptionLog(e);
			result.setResultCode(ProcCodeConstants.PROC_CODE_100E7027);
		} catch (Exception ex) {
			BankLogUtils.printServiceImplExceptionLog(ex);
			result.setResultCode(ProcCodeConstants.PROC_CODE_100E7027);
		}
		return result;

	}

	@Override
	public Result refund(BaseMessage msg) throws GopayException {
		Result result = new Result(false);
		try {
			@SuppressWarnings("unchecked")
			PabTransResMsg<PayRefundResMsg> resMsg = (PabTransResMsg<PayRefundResMsg>) wcPayPabManager.refund(msg);
			if (resMsg != null) {
				if ("0".equals(resMsg.getErrcode()) && "0".equals(resMsg.getBody().getStatus())) {
					result.setDefaultModel(resMsg);
					result.setSuccess(true);
					// 接收成功
					result.setModel("falg", true);
				} else {
					result.setSuccess(false);
					result.setModel("falg", false);
					result.setResultCode(ProcCodeConstants.PROC_CODE_100E6087);
					result.setErrorMsg(resMsg.getMsg());
				}
			} else {
				result.setSuccess(false);
				result.setModel("falg", false);
				result.setResultCode(ProcCodeConstants.PROC_CODE_100E6087);
			}

		} catch (GopayException e) {
			BankLogUtils.printServiceImplExceptionLog(e);
			result.setResultCode(e.getErrCode());
		} catch (Exception e) {
			BankLogUtils.printServiceImplExceptionLog(e);
			result.setResultCode(ProcCodeConstants.PROC_CODE_100E6087);
		}
		return result;

	}

	@Override
	public Result refundQuery(BaseMessage msg) throws GopayException {
		Result result = new Result();
		try {
			@SuppressWarnings("unchecked")
			PabTransResMsg<PayRefundQueryResMsg> resMessage = (PabTransResMsg<PayRefundQueryResMsg>) wcPayPabManager
					.refundOrderQuery(msg);
			logger.info("---微信公众号/支付宝服务窗支付平安渠道订单查询返回处理对象：" + ToStringBuilder.reflectionToString(resMessage));
			resMessage.setAmount(msg.getAmount());
			result.setDefaultModel(resMessage);
			result.setSuccess(true);
		} catch (GopayException e) {
			BankLogUtils.printServiceImplExceptionLog(e);
			result.setResultCode(ProcCodeConstants.PROC_CODE_100E7027);
		} catch (Exception ex) {
			BankLogUtils.printServiceImplExceptionLog(ex);
			result.setResultCode(ProcCodeConstants.PROC_CODE_100E7027);
		}
		return result;

	}

	@Override
	public Result verify(BaseMessage msg) throws GopayException {

		Result result = new Result(false);
		try {

			//ScanPayServerNotifyMsg message = (ScanPayServerNotifyMsg) msg;
			WcPayNotifyMsg message = (WcPayNotifyMsg) msg;

			Boolean flag = (Boolean) wcPayPabManager.verify(message);
			result.setDefaultModel(flag);
			result.setSuccess(true);
			result.setModel("res", message);
			Map<String, String> param = new HashMap<String, String>(9);
			/**
			 * 验签成功
			 */
			if ((boolean) result.getDefaultModel()) {
				if (("0".equals(message.getPay_result()))) {
					param.put("orderId", message.getOrderId());
					param.put("amt", String.valueOf(message.getAmount()));
					param.put("cardType", "Unknown");
					param.put("notifyNum", "1");
					param.put("payStatus", "00");
					param.put("retCode", "00");
					param.put("retMsg", "验签成功");
					param.put("signData", "");
					param.put("isFront", String.valueOf(message.isFront()));
					result.setModel("isNotifyCashier", param);
					result.setOrderStatus(true);
				}
			} else {
				param.put("orderId", message.getOrderId());
				param.put("amt", String.valueOf(message.getAmount()));
				param.put("cardType", "Unknown");
				param.put("notifyNum", "1");
				param.put("payStatus", "01");
				param.put("retCode", "01");
				param.put("retMsg", "验签失败");
				param.put("signData", "");
				param.put("isFront", String.valueOf(message.isFront()));
				result.setModel("isNotifyCashier", param);
				result.setOrderStatus(false);
			}

		} catch (GopayException e) {
			BankLogUtils.printServiceImplExceptionLog(e);
			result.setResultCode(e.getErrCode());
		} catch (Exception ex) {
			BankLogUtils.printServiceImplExceptionLog(ex);
			result.setResultCode(ProcCodeConstants.PROC_CODE_100E6064);
		}
		return result;

	}

}
